<script setup>
import { ref, watch } from 'vue'
import { updateTrainingService } from '@/api/training.js'
import { message, Upload } from 'ant-design-vue'
import { useUserStore } from '@/stores'
import { PlusOutlined, InboxOutlined } from '@ant-design/icons-vue'

const userStore = useUserStore()
const headers = {
  adminToken: userStore.token
}

const open = ref(false)
const confirmLoading = ref(false)
const showModal = () => {
  open.value = true
}

defineExpose({ showModal })

const props = defineProps({
  trainingData: {
    type: Object
  },
  getTrainingList: {
    type: Function
  }
})
const trianingInfo = ref(props.trainingData)
const updateTrainingInfo = (newValue) => {
  trianingInfo.value = newValue

  if (trianingInfo.value.fileUrl)
    fileList.value = [
      {
        uid: '-1', // 唯一标识符，必须为字符串
        name: 'file.pdf', // 文件名称
        status: 'done', // 文件状态，表示已经上传完成
        url: trianingInfo.value.fileUrl // 文件地址
      }
    ]
  if (trianingInfo.value.imageUrl)
    previewImage.value = trianingInfo.value.imageUrl
  imgList.value = [
    {
      uid: '-1', // 唯一标识符，必须为字符串
      name: 'picture.png', // 文件名称
      status: 'done', // 文件状态，表示已经上传完成
      url: trianingInfo.value.imageUrl // 文件地址
    }
  ]
}

watch(
  () => props.trainingData,
  (newValue) => {
    updateTrainingInfo(newValue)
  }
)
console.log(props.trainingData)
//文件上传相关
const fileList = ref([])
const imgList = ref([])
const handlePdfChange = (info) => {
  const status = info.file.status
  if (status !== 'uploading') {
    console.log(info.file, info.fileList)
  }
  if (status === 'done') {
    message.success(`${info.file.name} 文件上传成功.`)
    trianingInfo.value.fileUrl = info.file.response.data
  } else if (status === 'error') {
    message.error(`${info.file.name} 文件上传失败.`)
  }
}
const handleImgChange = (info) => {
  const status = info.file.status
  if (status !== 'uploading') {
    console.log(info.file, info.fileList)
  }
  if (status === 'done') {
    message.success(`${info.file.name} 文件上传成功.`)
    trianingInfo.value.imageUrl = info.file.response.data
    previewImage.value = info.file.response.data
  } else if (status === 'error') {
    message.error(`${info.file.name} 文件上传失败.`)
  }
}

const beforePdfUpload = (file) => {
  const isPDF = file.type === 'application/pdf'
  if (!isPDF) {
    message.error('只能上传 PDF 文件！')
    return Upload.LIST_IGNORE
  }
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('文件大小不能超过 10MB！')
    return Upload.LIST_IGNORE
  }
  return true
}
const beforeImgUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('图片格式有误!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小必须小于2MB!')
  }
  return isJpgOrPng && isLt2M
}

//图片预览相关
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
  previewImage.value = ''
}
const handlePreview = async (file) => {
  previewVisible.value = true
  previewTitle.value =
    file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}

const changeTrainingInfo = async () => {
  if (
    trianingInfo.value.title === '' ||
    trianingInfo.value.tag === '' ||
    trianingInfo.value.description === '' ||
    trianingInfo.value.imageUrl === '' ||
    trianingInfo.value.fileUrl === ''
  ) {
    message.error('请填写完整信息！')
    return
  }
  //将tag数组转换为回字符串
  trianingInfo.value.tag = trianingInfo.value.tag.toString()
  confirmLoading.value = true
  console.log(trianingInfo.value)
  const res = await updateTrainingService(trianingInfo.value)
  if (res.data.code === 1) {
    message.success('信息修改成功！')
    trianingInfo.value = {
      title: '',
      fileUrl: '',
      imageUrl: '',
      description: '',
      tag: ''
    }
    fileList.value = []
    imgList.value = []
    props.getTrainingList()
    open.value = false
  } else {
    message.error('信息修改失败！')
  }
  confirmLoading.value = false
}
</script>
<template>
  <div>
    <a-modal
      v-model:open="open"
      title="培训活动详情"
      width="40%"
      :confirm-loading="confirmLoading"
    >
      <h2><b>培训基础信息</b></h2>

      <h3>培训标题</h3>
      <div class="components-input-demo-size">
        <a-input
          v-model:value="trianingInfo.title"
          size="middle"
          placeholder="描述培训标题"
          style="width: 40%"
          :maxlength="20"
        />
        <br />
        <br />
        <h3>培训标签</h3>
        <a-input
          v-model:value="trianingInfo.tag"
          size="middle"
          placeholder="如：AI科普，科学教育等，多个标签用逗号隔开"
          :maxlength="20"
          style="width: 40%"
        />
        <br />
        <br />
        <h3>培训简介</h3>
        <a-textarea
          v-model:value="trianingInfo.description"
          style="width: 60%"
          size="large"
          placeholder="请用一句话介绍这个培训的内容"
          :maxlength="100"
          allow-clear
        />
        <br />
        <br />
        <h3>培训封面</h3>
        <a-form-item label="">
          <a-upload
            :headers="headers"
            v-model:file-list="imgList"
            action="/aPi/web/admin/common/upload"
            list-type="picture-card"
            :max-count="1"
            @preview="handlePreview"
            :before-upload="beforeImgUpload"
            @change="handleImgChange"
          >
            <div>
              <PlusOutlined />
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <h2><b>培训具体信息</b></h2>
        <h3>培训相关文件</h3>
        <div style="width: 50%">
          <a-upload-dragger
            v-model:fileList="fileList"
            name="file"
            :before-upload="beforePdfUpload"
            :max-count="1"
            :headers="headers"
            action="/aPi/web/admin/common/upload"
            @change="handlePdfChange"
          >
            <p class="ant-upload-drag-icon">
              <inbox-outlined></inbox-outlined>
            </p>
            <p class="ant-upload-text">上传培训相关文件</p>
            <p class="ant-upload-hint">
              仅支持上传 PDF 文件，文件大小不能超过 10MB
            </p>
          </a-upload-dragger>
        </div>
      </div>
      <br />
      <a-space wrap style="display: flex; justify-content: center">
        <a-button
          type="primary"
          block
          size="large"
          @click="changeTrainingInfo()"
        >
          修改培训
        </a-button>
      </a-space>
      <template v-slot:footer> </template>
    </a-modal>
    <a-modal
      :open="previewVisible"
      :title="previewTitle"
      :footer="null"
      @cancel="handleCancel"
    >
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
